package com.jo.cch.activity;

import static com.jo.cch.utils.PinyinUtils.OnCancelClickListener;

import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatImageView;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.promeg.pinyinhelper.Pinyin;
import com.jo.cch.R;
import com.jo.cch.bean.LetterInfo;
import com.jo.cch.bean.WordInfo;
import com.jo.cch.dao.LearnLogDao;
import com.jo.cch.db.SPConstant;
import com.jo.cch.db.SpUtil;
import com.jo.cch.helper.PinyinDataHelper;
import com.jo.cch.helper.WordDataHelper;
import com.jo.cch.helper.YingyuDataHelper;
import com.jo.cch.sql.LearnLog;
import com.jo.cch.utils.DataUtils;
import com.jo.cch.utils.DateUtils;
import com.jo.cch.utils.PinyinUtils;
import com.jo.cch.utils.PublicUtils;
import com.jo.cch.utils.YuwenUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class YingyuchimeActivity extends Activity {

    private AppCompatImageView backIv;

    private TextView letter;

    private Button chime1, chime2, chime3;

    private List<LetterInfo> datas;

    private TextView tips;

    private int index = 0;

    private int yesIndex = 0;

    private int noIndex = 0;

    private String logId;

    private String startDate;

    private String type = "谐音";

    private String selectGroup, selectChild;

    private List<String> errorSs = new ArrayList<String>();

    private LearnLogDao learnLogDao;

    private TextView tv_time;

    private Toast mtoast;

    private Timer mTimer = null;

    private TimerTask mTimerTask = null;

    private Handler mHandler = null;

    private final static int START = 1;

    private final static int RE_START = 2;

    private int TOTAL_TIME = -1;

    private SoundPool soundPool; // 成功声音加载池

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yingyuchime);

        //第一个参数是可以支持的声音数量，第二个是声音类型，第三个是声音品质
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(this, R.raw.yes, 1);
        soundPool.load(this, R.raw.no, 1);
        letter = (TextView) findViewById(R.id.letter);
        tips = (TextView) findViewById(R.id.tips);

        tv_time = (TextView) findViewById(R.id.tv_time);
        TOTAL_TIME = (Integer) SpUtil.getInstance(this).getParam(SPConstant.YINGYU_FLAG,5);
        chime1 = (Button) findViewById(R.id.chime1);
        chime2 = (Button) findViewById(R.id.chime2);
        chime3 = (Button) findViewById(R.id.chime3);

        logId = UUID.randomUUID().toString();
        startDate = DateUtils.getDate(new Date(), null);
        learnLogDao = new LearnLogDao(this);

        datas = (List<LetterInfo>) getIntent().getExtras().getSerializable("yingyus");
        selectGroup = getIntent().getStringExtra("selectGroup");
        selectChild = getIntent().getStringExtra("selectChild");

        Collections.shuffle(datas);
        String letter = datas.get(index).getLetter();
        this.letter.setText(letter);
        tips.setText("共"+datas.size()+"个"+selectChild+"，已读0个，对0个，错0个");
        setChime(letter);

        chime1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (datas.size() > 0) {
                    String spy = chime1.getText().toString();
                    know(spy);
                }
            }
        });

        chime2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (datas.size() > 0) {
                    String spy = chime2.getText().toString();
                    know(spy);
                }
            }
        });

        chime3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String spy = chime3.getText().toString();
                know(spy);
            }
        });

        //返回
        backIv = (AppCompatImageView) findViewById(R.id.backIv);
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopTimer();
                finish();
            }
        });

        mHandler = new Handler() {
            int num = TOTAL_TIME;
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case START:
                        if (num == 0){
                            know("-");
                            num = TOTAL_TIME;
                        }else if (num < 0){
                            num = TOTAL_TIME;
                        }else{
                            num--;
                        }
                        tv_time.setText(String.valueOf(num));
                        break;
                    case RE_START:
                        num = TOTAL_TIME;
                        tv_time.setText(String.valueOf(num));
                        break;
                    default:
                        break;
                }
            }
        };

        startTimer();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
        soundPool.release();
    }

    public void know(String spy){
        index++;
        PublicUtils.addLog(YingyuchimeActivity.this, learnLogDao, logId, selectGroup, selectChild, type, datas.size() + "/" + index + "/" + yesIndex + "/" + noIndex, startDate, errorSs);
        if(datas.size() > index){
            String noWord = datas.get(index-1).getLetter();
            String chimeStr = YingyuDataHelper.letterChimeMap.get(noWord);
            String wordStr = datas.get(index).getLetter();
            setChime(wordStr);
            isSuccess(spy, chimeStr, noWord);
            setAnimatorTextView(wordStr, letter);
            sendMessage(RE_START);
        }else{
            stopTimer();
            String noWord = datas.get(index-1).getLetter();
            String chimeStr = YingyuDataHelper.letterChimeMap.get(noWord);
            isSuccess(spy, chimeStr, noWord);
            LearnLog log = learnLogDao.queryById(logId);
            String title = selectChild+"-"+log.getNo()+ "-1";
            YuwenUtils.showDialog(YingyuchimeActivity.this, new YuwenUtils.OnCancelClickListener() {
                @Override
                public void onCancelClickListener() {
                    setResult(2, getIntent());
                    stopTimer();
                    finish();
                }
            }, errorSs, datas.size(), yesIndex, noIndex, selectGroup, title);
        }
        tips.setText("共"+datas.size()+"个"+selectChild+"，已读"+index+"个，对"+yesIndex+"个，错"+noIndex+"个");
    }

    private void isSuccess(String spy, String chimeStr, String noWord){
        if(spy.equals(chimeStr)){
            yesIndex++;
            if(mtoast!=null){
                mtoast.cancel();//注销之前显示的那条信息
                mtoast=null;//这里要注意上一步相当于隐藏了信息，mtoast并没有为空，我们强制是他为空
            }
            if(mtoast==null) {
                mtoast = Toast.makeText(getApplicationContext(), "你真棒", Toast.LENGTH_SHORT);
                mtoast.setGravity(Gravity.CENTER, 0, 0);
                LinearLayout linearLayout = (LinearLayout) mtoast.getView();
                ImageView imageView = new ImageView(YingyuchimeActivity.this);
                imageView.setImageResource(R.drawable.laugh);
                linearLayout.addView(imageView, 0);
                mtoast.show();
            }
            soundPool.play(1, 1, 1, 0, 0, 1);
        }else{
            noIndex++;
            errorSs.add(noWord);
            if(mtoast!=null){
                mtoast.cancel();//注销之前显示的那条信息
                mtoast=null;//这里要注意上一步相当于隐藏了信息，mtoast并没有为空，我们强制是他为空
            }
            if(mtoast==null) {
                mtoast = Toast.makeText(getApplicationContext(), "错了哦", Toast.LENGTH_SHORT);
                mtoast.setGravity(Gravity.CENTER, 0, 0);
                LinearLayout linearLayout = (LinearLayout) mtoast.getView();
                ImageView imageView = new ImageView(YingyuchimeActivity.this);
                imageView.setImageResource(R.drawable.cry);
                linearLayout.addView(imageView, 0);
                mtoast.show();
            }
            soundPool.play(2, 1, 1, 0, 0, 1);
        }
    }

    private void setChime(String letter){
        List<String> pys = new ArrayList<>(3);
        String chimeStr1 = YingyuDataHelper.letterChimeMap.get(letter);
        pys.add(chimeStr1);

        List<LetterInfo> newChimeList = new ArrayList<>();
        for(LetterInfo l : datas){
            if(!l.getLetter().equals(letter)){
                newChimeList.add(l);
            }
        }
        Collections.shuffle(newChimeList);

        List<WordInfo> twoGradeD = WordDataHelper.getTwoGradeD(1);
        Collections.shuffle(twoGradeD);

        if(newChimeList.size() < 3){
            pys.add(twoGradeD.get(0).getWord());
            pys.add(twoGradeD.get(1).getWord());
        }else{
            String chimeStr2 = YingyuDataHelper.letterChimeMap.get(newChimeList.get(0).getLetter());
            if(pys.contains(chimeStr2)){
                pys.add(twoGradeD.get(0).getWord());
            }else{
                pys.add(chimeStr2);
            }

            String chimeStr3 = YingyuDataHelper.letterChimeMap.get(newChimeList.get(1).getLetter());
            if(pys.contains(chimeStr2)){
                pys.add(twoGradeD.get(0).getWord());
            }else{
                pys.add(chimeStr3);
            }

        }

        Collections.shuffle(pys);
        chime1.setText(pys.get(0));
        chime2.setText(pys.get(1));
        chime3.setText(pys.get(2));
    }

    private void setAnimatorTextView(String val, TextView tv){
        ValueAnimator animator = ValueAnimator.ofObject(new TypeEvaluator() {
            @Override
            public Object evaluate(float fraction, Object startValue, Object endValue) {
                TextView tv = (TextView) endValue;
                tv.setText(startValue.toString());
                return startValue;
            }
        }, val, tv);
        //动画时间
        animator.setDuration(800);
        animator.start();
    }

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(START);
                }
            };
        }
        if (mTimer != null && mTimerTask != null){
            mTimer.schedule(mTimerTask, 0, 1000);
        }
    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }
}
